<template>
  <DataTable url="smsMessage/list" ref="ds" pageable>
    <template #search="table">
      <Input type="text" v-model="table.params.phoneNumber" placeholder="手机号"/>
      <Input type="text" v-model="table.params.templateCode" placeholder="模板编号"/>
    </template>
    <template #tools="table">
      <Button v-if="PRIV_SEND" icon="jeicon-shipping" color="primary" @click="add">发送短信</Button>
    </template>
    <template #default="table">
      <Table :datas="table.data" :loading="table.loading" @trDblClick="edit" @select="selected" checkbox>
        <TableItem title="序号" prop="_index" :width="50"></TableItem>
        <TableItem title="手机号码" prop="phoneNumber" :width="120"></TableItem>
        <TableItem title="模板签名" prop="signName" :width="120"></TableItem>
        <TableItem title="模板编号" prop="templateCode" :width="120"></TableItem>
        <TableItem title="模板参数" prop="templateParam" :width="120"></TableItem>
        <TableItem title="发送时间" prop="createTime" :format="dateFormat" :width="120"></TableItem>
        <TableItem title="发送人" prop="createUser" :width="120"></TableItem>
        <TableItem title="状态" prop="status" :width="120"></TableItem>
        <TableItem title="说明" prop="memo" :width="120"></TableItem>
      </Table>
    </template>
  </DataTable>
  <Dialog href="sms/smsMessageDialog.vue" ref="dlg" hasDivider hasCloseIcon>
    <template #header>短信信息</template>
    <template #footer="dlg">
      <Button :loading="dlg.loading" color="primary" @click="dlg.cancel">确认</Button>
    </template>
  </Dialog>
  <Modal v-model="showSmsSend" hasCloseIcon :closeOnMask="false">
    <template #header>发送短信</template>
    <Form :model="sendData" :rules="sendRule" style="width:500px" ref="smsFormRef">
      <FormItem label="手机号" prop="phone" required>
        <Input v-model="sendData.phone"/>
      </FormItem>
      <FormItem label="短信签名" prop="signName" required>
<!--        <Input v-model="sendData.signName"/>-->
        <Select v-model="sendData.signName" :datas="signs" :deletable="false"/>
      </FormItem>
      <FormItem label="模板编号" prop="templateCode" required>
<!--        <Input v-model="sendData.templateCode" placeholder="如:SMS_123456789"/>-->
        <Select v-model="sendData.templateCode" :datas="templates" @change="onTemplateChange" :deletable="false"/>
      </FormItem>
      <FormItem label="模板参数" prop="templateParam" required>
          <Textarea v-model="sendData.templateParam" style="height: 100px;resize: none;"
                    placeholder='JSON格式参数'/>
      </FormItem>
      <FormItem label="模版内容" readonly>
          <Textarea v-model="templateContent" readonly style="height: 100px;resize: none;"/>
      </FormItem>
    </Form>
    <template #footer>
      <Button :loading="smsSending" color="primary" @click="sendSms">发送</Button>
    </template>
  </Modal>
</template>
<script setup>
import {ajax, util, hasPermission,toRef} from 'framework'
import {ref, reactive} from 'vue'
const signs=toRef(ajax.get("smsMessage/signs").then(r=>r.data.map(it=>it.SignName)))
const templates=toRef(ajax.get("smsMessage/templates").then(r=>r.data.map(it=>({key:it.TemplateCode,title:`${it.TemplateName}(${it.TemplateCode})`,content:it.TemplateContent}))))

//权限
const PRIV_SEND = hasPermission('sms.smsMessage.send');

//数据集
const ds = ref({})
const showSearch = ref(false), selects = ref([]);
const showSmsSend = ref(false), smsSending = ref(false)
//对话框的引用,可通过dlg.value.ref获取页面的引用
const dlg = ref({}), smsFormRef = ref(),templateContent=ref('')
const sendData = reactive({
  phone: "",
  signName: "",
  templateCode: "",
  templateParam: "{\n \"code\":\"12345\"\n}"
})
function extractVariables(str) {
  const regex = /\$\{(\w+)\}/g;
  let match;
  const variables = [];
  while ((match = regex.exec(str))) {
    variables.push(match[1]); // 添加变量名到数组中
  }
  return variables;
}
function onTemplateChange(v){
  if (!v){
    return
  }
  let content=v.content;
  templateContent.value=content
  let vars=extractVariables(content)
  let obj={}
  for (let v of vars){
    obj[v]=""
  }
  sendData.templateParam = JSON.stringify(obj, null, 2);
}
const sendRule = {
  mobile: ['phone'],
  rules: {
    templateCode: {
      valid: {
        pattern: /^SMS_[0-9]{9}$/,
        message: '不正确'
      },
    },
    templateParam: {
      valid(prop, parent, data) {
        try {
          JSON.parse(prop)
        } catch (e) {
          return '必须是正确的JSON格式'
        }
        return true;
      }
    }
  }
}

const dateFormat = util.format("yyyy-MM-dd HH:mm")

function search() {
  selects.value = []
  ds.value.reload()
}

function selected(v) {
  selects.value = v.map(it => util.fields(it, 'id'))
}

//打开发送短信窗口
function add() {
  showSmsSend.value = true
  smsSending.value = false
}

//发送短信
function sendSms() {
  var validResult = smsFormRef.value.valid();
  if (validResult.result) {
    smsSending.value = true
    ajax.post('smsMessage/send', sendData).then(r => {
      HeyUI.message("已发送")
      search()
      showSmsSend.value = false
    }).catch(e => {
    }).finally(f => smsSending.value = false)
  }
}

function editFirst() {
  if (selects.value.length == 0) {
    return;
  }
  edit(selects.value[0])
}

function edit(v) {
  dlg.value.open(util.fields(v, 'id'))
}


</script>
